import { menuTree } from '@/apis/personal';
import PageFrame from '@/layout/components/PageFrame.vue';
import Layout from '@/layout/index.vue';
import { useUserStore } from '@/store/user';
import { useCommonStore } from '@/store/common';
import { createRouter, createWebHashHistory } from 'vue-router';

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Layout,
    children: [
      {
        path: 'login',
        name: 'Login',
        component: () => import('@/views/login/index.vue'),
      },
      {
        path: '404',
        name: 'NotFound',
        component: () => import('@/views/404.vue'),
      },
      // {
        // path: '/app',
        // name: 'App',
        // component: () => import('@/views/app/index.vue'),
      // },
      {
        path: 'personal',
        name: 'Personal',
        meta: {
          requireAuth: true,
        },
        component: () => import('@/views/personal/index.vue'),
        children: [
          {
            path: 'message',
            name: 'PersonalMessage',
            meta: {
              requireAuth: true,
            },
            component: () => import('@/views/personal/Message.vue'),
          },
        ],
      },
    ],
  },
];

const route404 = {
  path: '/:pathMatch(.*)*',
  name: '404',
  redirect: '/404',
};

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

router.beforeEach(async (to) => {
  const userStore = useUserStore();
  const commonStore = useCommonStore();
  const isLogin = userStore.isLogin;
  if (to.path === '/login') {
    if (isLogin) {
      return { name: 'Home' };
    }
    return true;
  }

  if (to.meta.requireAuth) {
    if (!isLogin) {
      return { name: 'Login' };
    }
  }

  await addDynamic();
  if (!to.name && hasRoute(to)) {
    return { ...to };
  }
  if (to.path === '/' && commonStore.firstRoute) {
    return commonStore.firstRoute;
  }

  return true;
});

function hasRoute(to) {
  const item = router.getRoutes().find(item => item.path === to.path);
  return !!item;
}

function addDynamic() {
  const commonStore = useCommonStore();
  if (commonStore.routeLoaded) {
    return;
  }
  // 添加动态路由
  return menuTree().then((res) => {
    if (res.data && res.data.length) {
      addDynamicRoutes(res.data);
    }
    router.addRoute(route404);
    commonStore.setRouteLoaded(true);
    // 保存菜单树
    commonStore.setMenuTree(res.data);
  });
}

// 获取views 下的所有视图组件path 作为key， 组件对象作为value
const modules = import.meta.glob('../views/**/*.vue');

function addDynamicRoutes(data, parent) {
  const commonStore = useCommonStore();
  data.forEach((item, i) => {
    const route = {
      path: item.path,
      name: item.name,
      meta: {
        title: item.title,
        icon: item.icon,
      },
      children: [],
    };
    if (parent) {
      if (item.parentId !== 0) {
        const compParr = item.path.replace('/', '').split('/');
        const l = compParr.length - 1;
        const compPath = compParr
          .map((v, i) => {
            return i === l
              ? v.replace(/\w/, (L) => L.toUpperCase()) + '.vue'
              : v;
          })
          .join('/');
        route.path = compParr[l];
        route.component = modules[`../views/${compPath}`];
        console.log(compPath);
        parent.children.push(route);
      }
    } else {
      if (item.children && item.children.length) {
        route.redirect = item.children[0].path;
        addDynamicRoutes(item.children, route);
      }
      // 设定一级菜单的组件
      const compPath = item.path.replace('/', '');
      // route.component = PageFrame;
      route.component = modules[`../views/${compPath}/index.vue`];
      if (i === 0) {
        commonStore.setFirstRoute(route);
      }
      router.addRoute('Home', route);
    }
  });
}

export default router;
